<template>
	<view>
		<view class="uni-header">
			<view style="font-size:16px;padding:15px;background: #fff;">
				<uni-breadcrumb separator="/">
					<uni-breadcrumb-item v-for="(route,index) in routes" :key="index" :to="route.to">
						{{route.name}}
					</uni-breadcrumb-item>
				</uni-breadcrumb>
			</view>
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini"
					@click="navigateTo('./add?store='+store+'&store_id='+store_id+'&category_id='+category_id)">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">导出 Excel</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :where="where" page-data="replace" :orderby="orderby"
				:getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{data,pagination,loading,error,options}" :options="options" loadtime="manual"
				@load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">

					<uni-tr>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'images')">商品照片</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'name')" sortable
							@sort-change="sortChange($event, 'name')">名称</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'shop_id')">所属店铺</uni-th>
						<uni-th align="center">所属分类</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'goods_sn')" sortable
							@sort-change="sortChange($event, 'goods_sn')">货号</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'ingredients')"
							sortable @sort-change="sortChange($event, 'ingredients')">主料</uni-th>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'month_sales')"
							sortable @sort-change="sortChange($event, 'month_sales')">月销量</uni-th>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'total_sales')"
							sortable @sort-change="sortChange($event, 'total_sales')">总销量</uni-th>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'price')" sortable
							@sort-change="sortChange($event, 'price')">商品价格</uni-th>
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'other_price')"
							sortable @sort-change="sortChange($event, 'other_price')">美团/饿了么价格</uni-th>
						
						<uni-th align="center" >
							首页展示
						</uni-th>
						<uni-th align="center">
							秒杀活动
						</uni-th>
						<uni-th align="center" >
							设置零元
						</uni-th>
						<uni-th align="center" >
							商品必选
						</uni-th>
						
						<uni-th align="center" filter-type="search"
							@sort-change="sortChange($event, 'create_uid')">创建人</uni-th>
						<uni-th align="center" filter-type="timestamp" @filter-change="filterChange($event, 'create_date')"
							sortable @sort-change="sortChange($event, 'create_date')">创建时间</uni-th>
						
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">

						<uni-td align="center">
							<image :src="item.images[0].url+'?x-oss-process=image/resize,m_fixed,h_100,w_100'"
								style="width:35px;height:35px; border-radius:5px;"></image>
						</uni-td>
						<uni-td align="center">
							<text class="titleApp">
								{{item.name}}
							</text>
						</uni-td>
						<uni-td align="center">{{item.shop_id && item.shop_id[0] && item.shop_id[0].shop_title}}</uni-td>
						<uni-td
							align="center">{{item.category_id && item.category_id[0] && item.category_id[0].text}}</uni-td>
						<uni-td align="center">{{item.goods_sn}}</uni-td>
						<uni-td align="center">{{item.ingredients||"--"}}</uni-td>
						<uni-td align="center">{{item.month_sales}}</uni-td>
						<uni-td align="center">{{item.total_sales}}</uni-td>

						<uni-td align="center">
							<text class="fontColorApp">
								￥{{(item.price / 100).toFixed(2)||"--"}}
							</text>
						</uni-td>
						<uni-td align="center">
							<text class="fontColorApp">
								￥	{{(item.other_price / 100).toFixed(2)||"--"}}
							</text>
						</uni-td>
						<uni-td align="center">
							<switch :checked="item.is_index"   style="transform:scale(0.9)" @change="changeIsIndex(item._id,$event,item.name,index)" />
						</uni-td>
						<!-- 秒杀活动 -->
						<uni-td align="center">
							<text :style="`color:#${item.seckill?  item.seckill.time > Date.now() ? 'ff3300':'555'  :'999'}`" >
								{{ item.seckill?  item.seckill.time > Date.now() ? '参加中':'已过期'  :'未参加' }}
							</text>
							<text class="util_text" 
								@click="openSeckillPop(item)"
							>
								设置
							</text>
						</uni-td>
						<!-- 零元购 -->
						<uni-td align="center">
							{{!item.special?'未参加':'已参加'}}
							<switch :checked="item.special"   style="transform:scale(0.9)" @change="changeIsSpecial(item._id,$event,item.name,index)" />
						</uni-td>
						<!-- 商品必选 -->
						<uni-td align="center">
							{{item.mandatoy?'需必选':'非必选'}}
							<switch :checked="item.mandatoy"   style="transform:scale(0.9)" @change="changeIsMandatoy(item._id,$event,item.name,index)" />
						</uni-td>
						<uni-td align="center">{{item.create_uid && item.create_uid[0] && item.create_uid[0].name}}</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.create_date"></uni-dateformat>
						</uni-td>
						
						<uni-td align="center">
							<view class="uni-group">
								<button
									@click="navigateTo('./edit?id='+item._id+'&store='+item.shop_id[0].shop_title+'&store_id='+item.shop_id[0]._id, false)"
									class="uni-button" size="mini" type="primary">修改</button>
								<button @click="confirmDelete(item)" class="uni-button" size="mini" type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
					
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
	</view>
		<uni-popup ref="popupSeckill"  border-radius="10px 10px 0 0">
			<view class="popupSeckill">
				秒杀活动设置
				<view style="margin:20px 0">
					<text style="color:#555" >
						{{tempSeckill.name}}
					</text>
					 | 商品现价: ￥{{(tempSeckill.price / 100).toFixed(2)}}
				</view>
				<uni-forms :modelValue="formData"  ref="form" :rules="rules" >
					<uni-forms-item label="结束时间" name="time">
						<uni-datetime-picker returnType="timestamp"
							v-model="formData.time" @change="changeLog($event)"
							:start="Date.now()+(1000 * 60 * 60 * 24)"
						/>
					</uni-forms-item>
					<uni-forms-item label="秒杀价格" name="price">
						<uni-easyinput type="number" v-model="formData.price" placeholder="请输入秒杀价格(￥)" />
					</uni-forms-item>
					<uni-forms-item label="总数量" name="number">
						<uni-easyinput type="number" v-model="formData.number" placeholder="请输入总数量" />
					</uni-forms-item>
					<uni-forms-item label="数量" name="quota">
						<uni-easyinput type="number" v-model="formData.quota" placeholder="请输入数量" />
					</uni-forms-item>
					
					<view class="util-button">
						<view >
							<button type="primary" class="uni-button" @click="submitSeckill" >
								保存
							</button>
						</view>
						<view style="margin-top: 10px;" @click="this.$refs.popupSeckill.close()" >
							<button type="warn" class="uni-button" >
								关闭
							</button>
						</view>
					</view>
				</uni-forms>
			</view>
		</uni-popup>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../../js_sdk/validator/goods.js';
	const global = uniCloud.importObject("global", {customUI: true})
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'id desc,create_date desc' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {

		data() {
			let that = this;
			return {
				// 面包屑
				routes: [{to: "/pages/index/index",name: "首页",},
					{to: "",name: "店铺列表",},
					{to: "",name: "店铺管理",},
					{to: "",name: "商品管理",},
				],
				groupBy: 'shop_id,category_id',
				store: '',
				goods: that.goodsWhere,
				store_id: '',
				category_id: '',
				collectionList: [db.collection('goods').where(that.goodsWhere).field(
					'category_id,shop_id,goods_sn,name,ingredients,seckill,accessories,month_sales,special,mandatoy,total_sales,description,images,price,goods_options,price,other_price,comment_total,sku,create_uid,create_date'
					).getTemp(), db.collection('shop-categories').field('_id,title as text').getTemp(), db.collection(
					'shop').field('_id,title as shop_title').getTemp(), db.collection('uni-id-users').field(
					'_id,nickname as name').getTemp()],
				query: '',
				where: "",
				goodsWhere: 'ewew',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				// 秒杀设置
				formData:{
					price:'',
					number:'',
					quota:'',
					time:''
				},
				// 校验
				rules: {
					price: {
						rules: [
							{ required: true,errorMessage: '请设置秒杀金额' },
						]
					},
					number: {
						rules: [
							{ required: true,errorMessage: '请设置秒杀总数量' },
						]
					},
					quota: {
						rules: [
							{ required: true,errorMessage: '请设置秒杀数量' },
							{
								required: true,
								validateFunction: (rule,value,data,callback) => {
									if (parseInt(value ) > parseInt(this.formData.number) ) {
										callback('每人可抢数量不能大于总数量');
									} else {
										callback();
									}
							  },
							},
						]
					},
					time: {
						rules: [
							{ required: true,errorMessage: '请设置秒杀结束时间' },
						]
					}
				},
				tempSeckill:{},	// 临时存放秒杀数据
				exportExcel: {
					"filename": "goods.xls",
					"type": "xls",
					"fields": {
						"category_id": "category_id",
						"shop_id": "shop_id",
						"货号": "goods_sn",
						"名称": "name",
						"主料": "ingredients",
						"辅料": "accessories",
						"月销量": "month_sales",
						"总销量": "total_sales",
						"详细描述": "description",
						"商品照片": "images",
						"goods_options": "goods_options",
						"秒杀活动": "seckill",
						"商品原价": "price",
						"商品现价": "new_price",
						"美团/饿了么价格": "other_price",
						"评价总数": "comment_total",
						"sku": "sku",
						"创建人": "create_uid",
						"首页展示": "is_index",
						"创建时间": "create_date"
					}
				},
				exportExcelData: []
			}
		},
		onLoad(e) {
			if (e.category_id) {
				this.routes =[{to: "/pages/index/index",name: "首页",},
					{to: "",name: "商铺列表",},
					{to:`/pages/shop/shop-categories/list?store_id=${e.store_id}&store=${e.store}`,name:"分类管理" },
					{to: "",name: "商品管理"}
				]
				this.collectionList = [db.collection('goods').where('shop_id=="' + e.store_id + '" && category_id=="' + e
					.category_id + '"').field(
					'category_id,shop_id,goods_sn,name,seckill,ingredients,is_index,accessories,special,mandatoy,month_sales,total_sales,description,images,goods_options,price,old_price,new_price,other_price,comment_total,sku,create_uid,create_date'
					).getTemp(), db.collection('shop-categories').field('_id,title as text').getTemp(), db.collection(
					'shop').field('_id,title as shop_title').getTemp(), db.collection('uni-id-users').field(
					'_id,nickname as name').getTemp()];
			} else {
				this.routes[1] ={
					to:'/pages/shop/shop/list',name:"商铺列表"
				} 
				this.collectionList = [db.collection('goods').where('shop_id=="' + e.store_id + '"').field(
					'category_id,shop_id,goods_sn,name,seckill,ingredients,special,mandatoy,accessories,month_sales,total_sales,description,images,price,goods_options,old_price,new_price,other_price,comment_total,sku,create_uid,create_date'
					).getTemp(), db.collection('shop-categories').field('_id,title as text').getTemp(), db.collection(
					'shop').field('_id,title as shop_title').getTemp(), db.collection('uni-id-users').field(
					'_id,nickname as name').getTemp()];
			}

			this.store = e.store;
			this.store_id = e.store_id;
			this.category_id = e.category_id;
			this._filter = {}
		},
		onReady(e) {
			this.$refs.udb.loadData()
		},
		methods: {
			// 提交秒杀活动修改设置
			submitSeckill(){
				this.$refs.form.validate().then(res=>{
					let form = {
						price : parseFloat((res.price *100 ).toFixed(0) ),
						number : parseFloat( res.number ),
						quota : parseFloat( res.quota ),
						time:res.time
					}
					global.updateDataToDatabase("goods",{seckill:form},{_id:this.tempSeckill._id }).then(res=>{
						uni.showToast({title: "设置成功" ,mask:true})
						this.$refs.popupSeckill.close()
						this.$nextTick(() => {
							this.loadData()
						})
					})
				}).catch(err =>{
					console.log('表单错误信息：');
				})
				// uni.showModal({
				// 	title:"哈哈"
				// })
			},
			// 秒杀活动设置
			openSeckillPop(item){
				this.tempSeckill = item
				let data = item.seckill;
				if(data){
					this.formData = {
						price: parseFloat( (data.price / 100 ).toFixed(0) ),
						number: parseFloat( data.number ),
						quota:parseFloat( data.quota ),
						time:data.time
					}
				}else{
					this.formData = {price:'',number:'',quota:'',time:''}
				}
				this.$refs.popupSeckill.open('center')
				setTimeout(()=>{
					this.$refs.form.setRules(this.rules)
				},500)
			},
			changeLog(e){
				this.formData.time = e
			},
			onqueryload(data) {
				this.exportExcelData = data
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			// 是否首页展示
			changeIsIndex(ID,event,name,index){
				let val = event.detail.value
				this.exportExcelData[index].is_index = val
				db.collection("goods").doc(ID).update({is_index:val}).then(res=>{
					uni.showToast({
						title:'‘'+name+'’'+'设置成功'
					})
				}).catch(error=>{
					uni.showToast({
						title:name+'设置失败',
						icon:"error"
					})
				})
			},
			// 设置零元购
			changeIsSpecial(ID,event,name,index){
				let val = event.detail.value
				this.exportExcelData[index].special = val
				val = val? 1 : 0
				db.collection("goods").doc(ID).update({special:val}).then(res=>{
					uni.showToast({
						title:'‘'+name+'’'+'设置成功'
					})
				}).catch(error=>{
					uni.showToast({
						title:name+'设置失败',
						icon:"error"
					})
				})
			},
			// 设置零元购
			changeIsMandatoy(ID,event,name,index){
				let val = event.detail.value
				this.exportExcelData[index].mandatoy = val
				db.collection("goods").doc(ID).update({mandatoy:val}).then(res=>{
					uni.showToast({
						title:'‘'+name+'’'+'设置成功'
					})
				}).catch(error=>{
					uni.showToast({
						title:name+'设置失败',
						icon:"error"
					})
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			//删除
			confirmDelete(item) {
				this.$refs.udb.remove(item._id, {
					success: (res) => {
						const database = uniCloud.importObject('shop');
						database.setShopGoodsNumberInc(item.shop_id[0]._id, -1);
						database.setShopCategoriesGoodsNumberInc(item.category_id[0]._id, -1);
						// const common = uniCloud.importObject('own-common');
						// common.delFile(item.images[0].fileID);
						database.deleteShopKeyword(item.shop_id[0]._id, item.name);
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			}
		}
	}
</script>

<style>
	.util-button{
		margin:20px 0;
	}
	.popupSeckill{
		margin-top: -20vh;
		width:500px;
		height:400px;
		padding:20px;
		border-radius:10px;
		color:#777;
		background:#fff;
	}
	.util_text{
		cursor:pointer;
		font-size:13px;
		color:#1abc9c;
	}
</style>